import {
  login,
  logout,
  getInfo
} from '@/api/user'
/* import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth' */
import router, {
  constantRoutes,
  anyRouters,
  resetRouter,
  dynamicRoutes
} from '@/router'

import cloneDeep from "lodash/cloneDeep"

const ProcessorRouters = (UserRouters, dynamicRoutes) => {
  console.log(333,dynamicRoutes)
  //UserRouters,用户可以访问权限路由的名称组成的数组
  //dynamicRoutes，所有动态路由对象组成的数组
  const re = dynamicRoutes.filter(item => {
    if (UserRouters.indexOf(item.name) !== -1) {
      console.log(UserRouters.indexOf(item.name))
      if (item.children && item.children.length) {
        //递归查找符合条件的二级路由，然后把二级路由整体改为符合条件的二级路由
        item.children = ProcessorRouters(UserRouters, item.children)
      }
      return true
    }
  })
  console.log(4444,re)
  return re

}

const getDefaultState = () => {
  return {
    token: localStorage.getItem("token_key"),
    name: '',
    avatar: '',
    routes: [],
    buttons: [],
    roles: [],
    Myroutes: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_DATA: (state, data) => {
    state.buttons = data.buttons
    state.roles = data.roles
    state.name = data.name
    state.avatar = data.avatar
  },
  SET_USER_DATA_ROUTERS: (state, routers) => {
    state.Myroutes = routers
    console.log(5555,routers)
    state.routes = constantRoutes.concat([...routers, anyRouters])
    //动态注册
    router.addRoutes([...routers, anyRouters])
  }
}

const actions = {
  // user login

  async login({
    commit
  }, userInfo) {
    const {
      username,
      password
    } = userInfo
    try {
      const re = await login({
        username: username.trim(),
        password: password
      })
      if (re.code === 20000 || re.code === 200) {
        const {
          data
        } = re
        commit('SET_TOKEN', data.token)
        localStorage.setItem("token_key", data.token)
      } else {
        this.$message.error("获取用户信息失败")
      }
    } catch (error) {
      this.$message.error("请求获取用户信息失败")
    }

  },
  // get user info
  async getInfo({
    commit,
    state
  }) {
    const response = await getInfo(state.token)
    const {
      data
    } = response

    if (!data) {
      return reject('Verification failed, please Login again.')
    }
    commit("SET_USER_DATA", data)
    console.log(222,data.routes)
    const UserRouters = ProcessorRouters(data.routes, cloneDeep(dynamicRoutes))
    commit("SET_USER_DATA_ROUTERS", UserRouters)
  },

  // user logout
  async logout({
    commit,
    state
  }) {
    try {
      const re = await logout(state.token)
      if (re.code === 20000 || re.code === 200) {
        localStorage.removeItem("token_key")
        resetRouter()
        commit('RESET_STATE')
      } else {
        this.$message.error("删除用户信息失败")
      }
    } catch (error) {
      this.$message.error("请求删除用户信息失败")
    }
  },

  // remove token
  resetToken({
    commit
  }) {
    localStorage.removeItem("token_key") // must remove  token  first
    commit('RESET_STATE')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
